<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\Admin;
use app\common\model\Banner;
use app\common\model\Company;
use app\common\model\factory\Category;
use app\common\model\forest\Member;
use app\common\model\Goods;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\shop\Data;
use app\common\model\User;
use app\common\model\wash\Order;
use app\common\model\wash\Serviceorder;
use fast\Random;
use think\Db;

/**
 * 工厂端接口
 */
class Factory extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];



    //工厂列表
    public function lists()
    {
        $param = $this->request->param();
        extract($param);
        $factory = $this->auth->getUser();
        $cate =  collection(Category::where('admin_id', $factory['company_id'])->select())->toArray();
        $arr = [];
        foreach ($cate as $v) {
            $where = [
                'company_id' => $factory['company_id'],
                'role' => 'factory',
                'category_id' => $v['id'],
            ];
            // $list['name'] =$v['title'];

            if ($factory['category_id'] == $v['id']) {
                $arr[] = [
                    'name' => $v['title'],
                    'list' => collection(User::where($where)->where('id', $factory['id'])->select())->toArray(),
                ];
            } else {
                $arr[] = [
                    'name' => $v['title'],
                    'list' => collection(User::where($where)->select())->toArray()
                ];
            }
        }
        $this->success('', $arr);
    }

    /**
     * 新增门店
     *
     */
    public function add_edit_shop()
    {
        $post = $this->request->post();
        extract($post);
        $factory =  $this->auth->getUser();
        if (!$nickname) {
            $this->error('门店名称不能为空');
        }
        if (!$address) {
            $this->error('门店地址不能为空');
        }
        if (!$lng || !$lat) {
            $this->error('经纬度不能为空');
        }
        if (!$username) {
            $this->error('登录账号不能为空');
        }
        if (!$password && !$id) {
            $this->error('登录密码不能为空');
        }
        if (!$avatar) {
            $this->error('门头不能为空');
        }
        if (!$factory_data) {
            $this->error('请绑定工厂');
        }
        $post['role'] = 'shop';
        Db::startTrans();
        try {
            $post['factory_id'] = $factory['id'];
            $post['company_id'] = $factory['company_id'];
            if ($password) {
                $post['salt'] = Random::alnum();
                $post['password'] = md5(md5($password) .  $post['salt']);
            } else {
                unset($post['password']);
            }
            $model = new User();
            if (isset($id) && $id) {
                $model = $model->get($id);
                $res = $model->isUpdate(true)->allowField(true)->save($post);
            } else {
                $post['status'] = 'normal';
                $res = $model->isUpdate(false)->allowField(true)->save($post);
            }
            if ($res) {
                foreach ($factory_data as &$v) {
                    $v['shop_id'] = $model->id;
                }
                $data = new Data();
                Data::where('shop_id', $model->id)->delete();
                $data->allowField(true)->saveAll($factory_data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败');
        }
        $this->success('成功');
    }
    /**
     * 门店列表
     *
     */
    public function shop_list()
    {
        $factory = $this->auth->getUser();
        $shop_ids = Data::where('factory_id', $factory->id)->column('shop_id');
        if ($shop_ids) {
            $list = User::whereIn('id', $shop_ids)->paginate();
        }
        $this->success('', $list ?? []);
    }

    /**
     * 门店详情
     *
     */
    public function shop_info()
    {
        $param = $this->request->param();
        extract($param);
        $data = User::get($id, ['shopdata']);
        $this->success('', $data);
    }
    /**
     * 新增骑手
     *
     */
    public function add_edit_rider()
    {
        $post = $this->request->post();
        extract($post);
        if (!$nickname) {
            $this->error('姓名不能为空');
        }
        if (!$mobile) {
            $this->error('联系电话不能为空');
        }
        if (!$username) {
            $this->error('登录账号不能为空');
        }
        if (!$password && !$id) {
            $this->error('登录密码不能为空');
        }

        $post['role'] = 'rider';
        $post['factory_id'] = $this->auth->id;

        if ($password) {
            $post['salt'] = Random::alnum();
            $post['password'] = md5(md5($password) .  $post['salt']);
        } else {
            unset($post['password']);
        }

        $model = new User($post);
        if (isset($id) && $id) {
            $model = $model->get($id);
            $model->isUpdate(true)->allowField(true)->save($post);
        } else {
            if ($mobile && User::getByMobile($mobile)) {
                $this->error('手机号码已存在');
            }
            $post['status'] = 'normal';
            $model->isUpdate(false)->allowField(true)->save($post);
        }
        $this->success('添加成功');
    }
    /**
     * 骑手列表
     *
     */
    public function rider_list()
    {
        $factory = $this->auth->getUser();
        $list = User::where('factory_id', $factory->id)->where('role', 'rider')->paginate();
        $this->success('', $list);
    }

    /**
     * 骑手详情
     *
     */
    public function rider_info()
    {
        $param = $this->request->param();
        extract($param);
        $data = User::get($id);
        $this->success('', $data);
    }

    /**
     * 骑手删除
     *
     */
    public function rider_del()
    {
        $param = $this->request->param();
        extract($param);
        $user =  User::get($id);
        $res = $user->delete();
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }

    /**
     * 新增服务员
     *
     */
    public function add_edit_cleaners()
    {
        $post = $this->request->post();
        extract($post);
        if (!$nickname) {
            $this->error('姓名不能为空');
        }
        if (!$mobile) {
            $this->error('联系电话不能为空');
        }
        if (!$username) {
            $this->error('登录账号不能为空');
        }
        if (!$password && !$id) {
            $this->error('登录密码不能为空');
        }

        $post['role'] = 'cleaners';
        $post['factory_id'] = $this->auth->id;

        if ($password) {
            $post['salt'] = Random::alnum();
            $post['password'] = md5(md5($password) .  $post['salt']);
        } else {
            unset($post['password']);
        }

        $model = new User($post);
        if (isset($id) && $id) {
            $model = $model->get($id);
            $model->isUpdate(true)->allowField(true)->save($post);
        } else {
            if ($mobile && User::getByMobile($mobile)) {
                $this->error('手机号码已存在');
            }
            $post['status'] = 'normal';
            $model->isUpdate(false)->allowField(true)->save($post);
        }
        $this->success('添加成功');
    }
    /**
     * 服务员列表
     *
     */
    public function cleaners_list()
    {
        $factory = $this->auth->getUser();
        $list = User::where('factory_id', $factory->id)->where('role', 'cleaners')->paginate();
        $this->success('', $list);
    }

    /**
     * 服务员详情
     *
     */
    public function cleaners_info()
    {
        $param = $this->request->param();
        extract($param);
        $data = User::get($id);
        $this->success('', $data);
    }

    /**
     * 服务员删除
     *
     */
    public function cleaners_del()
    {
        $param = $this->request->param();
        extract($param);
        $user =  User::get($id);
        $res = $user->delete();
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }
    /**
     * 常规订单列表
     *
     */
    public function order_list()
    {
        $param = request()->param();
        extract($param);
        $user = $this->auth->getUser();
        $order = new Order();
        if (isset($order_id) && $order_id) {
            $order->where('order.id', $order_id);
        }
        if (isset($keywords) && $keywords) {
            $order->whereLike('shop.mobile|factory.mobile|user.mobile|sn|phone', '%' . $keywords . '%');
        }
        if ($user['role'] == 'rider') {
            $factory_id = $user['factory_id'];
        } else {
            $factory_id = $user['id'];
        }
        $list = $order->with(['shop' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        }, 'user' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        }, 'goods' => function ($q) {
            // $q->with('cate');
        }, 'factory' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        },])->where('order.factory_id', $factory_id)->where('order.shop_status', '>', '0')->where('factory_status', (string) $type)->whereNotIn('order.status', ['0', '-1'])->paginate();
        $this->success('', $list);
    }



    /**
     * 家政订单列表
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="integer", required=false, sample="", description="ID")
     * @ApiParams (name="keywords", type="str", required=false, sample="", description="搜索")
     * @ApiParams (name="status", type="str", required=false, sample="", description="状态:1=待上门,2=清洗中,4=已完成")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function serviceorder_list()
    {
        $param = request()->param();
        extract($param);
        $user = $this->auth->getUser();
        $order = new Serviceorder();
        if (isset($order_id) && $order_id) {
            $order->where('fa_wash_serviceorder.id', $order_id);
        }
        if (isset($keywords) && $keywords) {
            $order->whereLike('shop.mobile|factory.mobile|user.mobile|sn|phone', '%' . $keywords . '%');
        }
        if ($user['role'] == 'cleaners') {
            $factory_id = $user['factory_id'];
        } else {
            $factory_id = $user['id'];
        }
        $list = $order->with(['shop' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        }, 'user' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        }, 'goods' => function ($q) {
            // $q->with('cate');
        }, 'factory' => function ($q) {
            $q->withField('id,nickname,avatar,mobile');
        },])->where('fa_wash_serviceorder.factory_id', $factory_id)->where('fa_wash_serviceorder.status', (string) $status)->whereNotIn('fa_wash_serviceorder.status', ['0', '-1'])->paginate();
        $this->responseMsg(0, $list);
    }


    /**
     * 家政订单详情
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function serviceorder_info()
    {
        $param = request()->param();
        extract($param);
        $data = Serviceorder::get($id, ['shop', 'user', 'goods']);
        $this->responseMsg(0, $data);
        // $this->success('', $data);
    }


    /**
     * 家政开始服务
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function serviceorder_in()
    {
        $param = request()->param();
        extract($param);
        $order = Serviceorder::get($id);
        if ($order->status != '1') {
            $this->error('订单状态错误');
        }
        $res = $order->allowField(true)->save(['status' => '2', 'warehousingtime' => time()]);
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 家政完成服务
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function serviceorder_complate()
    {
        $param = request()->param();
        extract($param);
        $order = Serviceorder::get($id);
        if ($order->status != '2') {
            $this->error('订单状态错误');
        }
        $res = $order->allowField(true)->save(['status' => '4', 'taketime' => time()]);

        User::servicecommission($order->money_fee + $order->pay_fee, $order->sn);
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }



    /**
     * 家政服务上传图片
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="before_images", type="str", required=false, sample="", description="清洗前图片，多图逗号分隔")
     * @ApiParams (name="after_images", type="str", required=false, sample="", description="清洗后图片，多图逗号分隔")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function serviceorder_take_pictures()
    {
        $param = request()->param();
        extract($param);
        $order = Serviceorder::get($id);
        if (!$order) {
            $this->error('未找到该订单');
        }
        $res = $order->allowField(true)->save($param);

        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }


    /**
     * 订单详情
     *
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        $data = Order::get($id, ['shop', 'user', 'goods']);
        $this->success('', $data);
    }

    /**
     * 拍照上传
     *
     */
    public function take_pictures()
    {
        $param = request()->param();
        extract($param);
        if (!isset($factory_f_image) || !$factory_f_image) {
            $this->error('请上传正面照');
        }
        if (!isset($factory_b_image) || !$factory_b_image) {
            $this->error('请上传背面照');
        }
        $order = Order::get($id);
        $res = $order->allowField(true)->save($param);
        if ($res) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    /**
     * 扫码进场
     *
     */
    public function sweep_approach()
    {
        $param = request()->param();
        extract($param);
        $order = Order::get($id);
        if ($order->shop_status != '1') {
            $this->error('订单状态错误');
        }
        $res = $order->allowField(true)->save(['factory_status' => '1', 'warehousingtime' => time()]);
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * 工厂数据
     *
     */
    public function factory_data()
    {
        $factory_id =  $this->auth->id;
        $data['turnover'] = Order::where('factory_id', $factory_id)->whereTime('paytime', 'today')->whereNotIn('status', ['0', '-1'])->sum('pay_fee+money_fee');
        $data['order_num'] = Order::where('factory_id', $factory_id)->whereTime('paytime', 'today')->whereNotIn('status', ['0', '-1'])->count();
        $data['commission'] = MoneyLog::where('user_id', $factory_id)->where('type', '2')->whereTime('createtime', 'today')->sum('money');
        $this->success('', $data);
    }

    /**
     * 门店总数据
     *
     */
    public function shop_data()
    {
        $param = request()->param();
        extract($param);
        $order = new Order;
        $money_log = new MoneyLog();
        $factory_id =  $this->auth->id;
        $order->whereNotIn('status', ['0', '-1']);
        if (isset($shop_id) && $shop_id) {
            $order->where('shop_id', $shop_id);
            $shop_ids = User::where('id', $shop_id)->value('id');
        } else {
            $order->where('factory_id', $factory_id);
            $shop_ids = User::where('factory_id', $factory_id)->column('id');
        }
        if ($type == 1) {
            $money_log->whereTime('createtime', 'month');
            $order->whereTime('paytime', 'month');
        } elseif ($type == 2) {
            $order->whereTime('paytime', 'week');
            $money_log->whereTime('createtime', 'week');
        } else {
            if (isset($starttime) && $starttime) {
                $order->where('paytime', '>', strtotime($starttime));
                $money_log->where('createtime', '>', strtotime($starttime));
            }
            if (isset($endtime) && $endtime) {
                $order->where('paytime', '<', strtotime($endtime . ' 23:59:59'));
                $money_log->where('createtime', '<', strtotime($endtime . ' 23:59:59'));
            }
        }
        $order->field('count(*) as num,factory_images,SUM(pay_fee+money_fee+credit_fee) as total_fee,FROM_UNIXTIME(paytime,"%Y年%m月%d日") as pay_time,FROM_UNIXTIME(paytime,"%m-%d") as time');
        $list = $order->group('pay_time')->order('paytime asc')->select();
        $money_log->field('SUM(money) as total_fee,FROM_UNIXTIME(createtime,"%Y年%m月%d日") as create_time,FROM_UNIXTIME(createtime,"%m-%d") as time');
        $money_log->whereIn('user_id', $shop_ids)->where('source_type', 200);
        $log = $money_log->group('create_time')->order('createtime asc')->select();
        $this->success('', compact('list', 'log'));
    }
}
